package org.example.demosql.Config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Arrays;

@Configuration
public class CorsFilterConfig {
    // 跨域过滤器
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilter() {
        FilterRegistrationBean<CorsFilter> corsFilterFilterRegistrationBean = new FilterRegistrationBean<>();  // 创建过滤器
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();  // 创建配置源
        CorsConfiguration corsConfiguration = new CorsConfiguration();  // 创建配置
        corsConfiguration.addAllowedHeader("*");   // 允许所有请求头
        corsConfiguration.addAllowedOriginPattern("*");   // 允许所有请求源
        corsConfiguration.setAllowCredentials(true);   // 允许携带cookie
//        corsConfiguration.setMaxAge(3600L);   // 有效期
        corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));   // 允许请求方法
        source.registerCorsConfiguration("/**", corsConfiguration);   // 注册配置
        corsFilterFilterRegistrationBean.setFilter(new CorsFilter(source));   // 设置过滤器
        corsFilterFilterRegistrationBean.setOrder(-1);   // 设置顺序
        return corsFilterFilterRegistrationBean;
    }
}